package com.example.qu_tao.View;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.qu_tao.Util.CaiGouDataManager;
import com.example.qu_tao.adapter.CaiGouAdapter;
import com.example.qu_tao.entity.CaiGouInfo;
import com.example.qu_tao.R;

import java.util.List;

public class CaigouGuanliActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private CaiGouAdapter adapter;
    private List<CaiGouInfo> caiGouInfoList;
    private ImageButton btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_caigouguanli);

        // 初始化控件
        initViews();

        // 初始化返回按钮
        initBackButton();

        // 初始化RecyclerView
        initRecyclerView();
    }

    private void initViews() {
        recyclerView = findViewById(R.id.recyclerView);
        btnBack = findViewById(R.id.btn_back);
    }

    private void initBackButton() {
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 结束当前Activity，返回卖家页面
                finish();
            }
        });
    }

    private void initRecyclerView() {
        // 获取采购信息数据
        caiGouInfoList = CaiGouDataManager.getInstance().getAllCaiGouInfo();

        // 添加调试日志
        Log.d("CaigouGuanliActivity", "Data list size: " + caiGouInfoList.size());
        for (CaiGouInfo info : caiGouInfoList) {
            Log.d("CaigouGuanliActivity", "Item: " + info.toString());
        }

        // 设置RecyclerView布局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 创建适配器
        adapter = new CaiGouAdapter(caiGouInfoList);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新数据
        refreshData();
    }

    private void refreshData() {
        // 重新获取数据
        List<CaiGouInfo> newData = CaiGouDataManager.getInstance().getAllCaiGouInfo();
        Log.d("CaigouGuanliActivity", "New data size: " + newData.size());

        // 如果数据有变化，更新适配器
        if (adapter == null) {
            initRecyclerView();
        } else {
            adapter.updateData(newData);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        // 处理物理返回键
        finish();
    }
}